/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PodcastPanel.java
 *
 * Created on May 4, 2009, 8:42:05 AM
 */
package com.bff.slimserver.musicjukebox.ui;

import com.bff.slimserver.music.exceptions.PlaylistException;
import com.bff.slimserver.musicjukebox.lib.JukeboxProperties;
import com.bff.slimserver.musicjukebox.lib.actions.AddFavoriteAction;
import com.bff.bjj.ui.component.BJJPanel;
import com.bff.bjj.ui.component.BJJButton;
import com.bff.slimserver.musicjukebox.ui.components.podcast.PodcastInfoPanel;
import com.bff.slimserver.musicjukebox.ui.components.podcast.PodcastItemList;
import com.bff.slimserver.musicjukebox.ui.components.podcast.PodcastItemListCellRenderer;
import com.bff.slimserver.musicjukebox.ui.components.podcast.PodcastTree;
import com.bff.bjj.utils.Utils;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JList;
import org.bff.slimserver.SlimPlaylist;
import org.bff.slimserver.SlimPodcaster;
import org.bff.slimserver.exception.SlimException;
import org.bff.slimserver.exception.SlimNetworkException;
import org.bff.slimserver.musicobjects.SlimPodcastItem;

/**
 *
 * @author Bill
 */
public class PodcastPanel extends javax.swing.JPanel {

    private SlimPlaylist playlist;
    private SlimPodcaster podcaster;
    private JukeboxProperties jp;
    private boolean loadingItems;

    /** Creates new form PodcastPanel */
    public PodcastPanel() {
        jp = JukeboxProperties.getInstance();
        try {
            this.playlist = jp.getPlaylist();
            this.podcaster = jp.getPodcaster();
        } catch (PlaylistException ex) {
            Logger.getLogger(PodcastPanel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SlimException ex) {
            Logger.getLogger(SongListTablePanel.class.getName()).log(Level.SEVERE, null, ex);
        }

        initComponents();

        btnFavorite.setEnabled(false);
        
        listPodcasts();

        loadProgressBar.setVisible(false);
        loadProgressItems.setVisible(false);
        loadDetailProgressBar.setVisible(false);

        jPanel4.setVisible(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel11 = new BJJPanel();
        jPanel5 = new javax.swing.JPanel();
        jPanel4 = new BJJPanel();
        jLabel1 = new javax.swing.JLabel();
        tfAddFeed = new javax.swing.JTextField();
        jPanel10 = new BJJPanel();
        btnAddFeed = new javax.swing.JButton();
        jPanel2 = new BJJPanel();
        jPanel1 = new BJJPanel();
        loadProgressBar = new javax.swing.JProgressBar();
        jScrollPane1 = new javax.swing.JScrollPane();
        podcastTree = new PodcastTree();
        jPanel3 = new BJJPanel();
        btnRefresh = new javax.swing.JButton();
        btnFavorite = new javax.swing.JButton();
        jPanel9 = new BJJPanel();
        lblError = new javax.swing.JLabel();
        lblError.setVisible(false);
        jPanel6 = new BJJPanel();
        jPanel7 = new BJJPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        podcastItemList = new PodcastItemList();
        loadProgressItems = new javax.swing.JProgressBar();
        jPanel8 = new BJJPanel();
        btnAddToPlaylist = new BJJButton();
        btnPlayNext = new BJJButton();
        btnClearAndPlay = new BJJButton();
        jPanel12 = new BJJPanel();
        loadDetailProgressBar = new javax.swing.JProgressBar();
        jPanel13 = new BJJPanel();
        podcastInfoPanel = new PodcastInfoPanel(true);

        setLayout(new java.awt.BorderLayout());

        jPanel11.setLayout(new java.awt.BorderLayout());

        jPanel5.setLayout(new java.awt.BorderLayout());

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Add New Feed"));
        jPanel4.setLayout(new java.awt.BorderLayout());

        jLabel1.setText("Podcast Feed:");
        jPanel4.add(jLabel1, java.awt.BorderLayout.WEST);

        tfAddFeed.setColumns(30);
        jPanel4.add(tfAddFeed, java.awt.BorderLayout.CENTER);

        btnAddFeed.setText("Add Feed");
        jPanel10.add(btnAddFeed);

        jPanel4.add(jPanel10, java.awt.BorderLayout.SOUTH);

        jPanel5.add(jPanel4, java.awt.BorderLayout.SOUTH);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Podcasts"));
        jPanel1.setLayout(new java.awt.BorderLayout());

        loadProgressBar.setIndeterminate(true);
        loadProgressBar.setString("Loading Podcasts");
        loadProgressBar.setStringPainted(true);
        jPanel1.add(loadProgressBar, java.awt.BorderLayout.SOUTH);

        podcastTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                podcastTreeValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(podcastTree);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel2.add(jPanel1, java.awt.BorderLayout.CENTER);

        btnRefresh.setText("Refresh");
        btnRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefreshActionPerformed(evt);
            }
        });
        jPanel3.add(btnRefresh);

        btnFavorite.setText("Add Favorite");
        jPanel3.add(btnFavorite);

        jPanel2.add(jPanel3, java.awt.BorderLayout.SOUTH);

        lblError.setFont(new java.awt.Font("Tahoma", 1, 12));
        lblError.setForeground(java.awt.Color.red);
        lblError.setText("Error");
        jPanel9.add(lblError);

        jPanel2.add(jPanel9, java.awt.BorderLayout.NORTH);

        jPanel5.add(jPanel2, java.awt.BorderLayout.CENTER);

        jPanel11.add(jPanel5, java.awt.BorderLayout.NORTH);

        jPanel6.setLayout(new java.awt.BorderLayout());

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Podcasts Items"));
        jPanel7.setLayout(new java.awt.BorderLayout());

        podcastItemList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                podcastItemListMouseClicked(evt);
            }
        });
        podcastItemList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                podcastItemListValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(podcastItemList);

        jPanel7.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        loadProgressItems.setIndeterminate(true);
        loadProgressItems.setString("Loading Podcast Items");
        loadProgressItems.setStringPainted(true);
        jPanel7.add(loadProgressItems, java.awt.BorderLayout.SOUTH);

        jPanel6.add(jPanel7, java.awt.BorderLayout.CENTER);

        btnAddToPlaylist.setText("Add to Playlist");
        btnAddToPlaylist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddToPlaylistActionPerformed(evt);
            }
        });
        jPanel8.add(btnAddToPlaylist);

        btnPlayNext.setText("Play Next");
        btnPlayNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPlayNextActionPerformed(evt);
            }
        });
        jPanel8.add(btnPlayNext);

        btnClearAndPlay.setText("Clear and Play");
        btnClearAndPlay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearAndPlayActionPerformed(evt);
            }
        });
        jPanel8.add(btnClearAndPlay);

        jPanel6.add(jPanel8, java.awt.BorderLayout.SOUTH);

        jPanel11.add(jPanel6, java.awt.BorderLayout.CENTER);

        add(jPanel11, java.awt.BorderLayout.CENTER);

        jPanel12.setBorder(javax.swing.BorderFactory.createTitledBorder("Podcast Details"));
        jPanel12.setMinimumSize(new java.awt.Dimension(500, 81));
        jPanel12.setPreferredSize(new java.awt.Dimension(500, 533));
        jPanel12.setLayout(new java.awt.BorderLayout());

        loadDetailProgressBar.setIndeterminate(true);
        loadDetailProgressBar.setString("Loading Podcast Details");
        loadDetailProgressBar.setStringPainted(true);
        jPanel12.add(loadDetailProgressBar, java.awt.BorderLayout.SOUTH);

        jPanel13.setLayout(new java.awt.BorderLayout());

        podcastInfoPanel.setMinimumSize(new java.awt.Dimension(500, 22));
        podcastInfoPanel.setPreferredSize(new java.awt.Dimension(500, 474));
        jPanel13.add(podcastInfoPanel, java.awt.BorderLayout.CENTER);

        jPanel12.add(jPanel13, java.awt.BorderLayout.CENTER);

        add(jPanel12, java.awt.BorderLayout.EAST);
    }// </editor-fold>//GEN-END:initComponents

    private void podcastItemListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_podcastItemListMouseClicked
        if (evt.getClickCount() == 2) {
        } else {
            JList lstCust = (JList) evt.getSource();
            int currIndex = lstCust.locationToIndex(evt.getPoint());
            Object currData = lstCust.getSelectedValue();
            Rectangle itemBounds = lstCust.getCellBounds(currIndex, currIndex);
            Point currPoint = new Point(evt.getX(), evt.getY());
            Component readyComponent = ((PodcastItemListCellRenderer) lstCust.getCellRenderer()).getListCellRendererComponent(lstCust,
                    currData, currIndex, true, true);
            readyComponent.setSize(itemBounds.width, itemBounds.height);
            Component pressedComponent = null;
            while (readyComponent != pressedComponent) {
                if (pressedComponent != null) {
                    readyComponent = pressedComponent;
                }
                pressedComponent = readyComponent.getComponentAt((int) (currPoint.getX() - itemBounds.getX()),
                        (int) (currPoint.getY() - itemBounds.getY()));

                if (pressedComponent == null) {
                    return;
                }
                currPoint.setLocation(currPoint.getX() - itemBounds.getX(), currPoint.getY() - itemBounds.getY());
                itemBounds = pressedComponent.getBounds();
            }

            if (pressedComponent instanceof JButton) {
                ((JButton) pressedComponent).doClick();
                //System.out.println("Pressed JButton with text " + ((JButton) pressedComponent).getText() + " in row " + currIndex + " of JList");
            }
        }
    }//GEN-LAST:event_podcastItemListMouseClicked

    private void btnAddToPlaylistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddToPlaylistActionPerformed
        this.setCursor(Utils.getHourglassCursor());
        try {
            for (SlimPodcastItem item : getPodcastItemList().getSelectedPodcasts()) {
                try {
                    getPlaylist().addPluginItem(getPodcaster().getPodcastAudioDetails(item));
                } catch (SlimNetworkException ex) {
                    Logger.getLogger(PodcastPanel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SlimException ex) {
                    Logger.getLogger(PodcastPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        } finally {
            this.setCursor(Utils.getNormalCursor());
        }
}//GEN-LAST:event_btnAddToPlaylistActionPerformed

    private void btnPlayNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlayNextActionPerformed
        this.setCursor(Utils.getHourglassCursor());
        try {
            for (SlimPodcastItem item : getPodcastItemList().getSelectedPodcasts()) {
                try {
                    getPlaylist().insertPluginItem(getPodcaster().getPodcastAudioDetails(item));
                } catch (SlimNetworkException ex) {
                    Logger.getLogger(PodcastPanel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SlimException ex) {
                    Logger.getLogger(PodcastPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } finally {
            this.setCursor(Utils.getNormalCursor());
        }
}//GEN-LAST:event_btnPlayNextActionPerformed

    private void btnClearAndPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearAndPlayActionPerformed
        this.setCursor(Utils.getHourglassCursor());
        try {
            for (SlimPodcastItem item : getPodcastItemList().getSelectedPodcasts()) {
                try {
                    getPlaylist().playPluginItem(getPodcaster().getPodcastAudioDetails(item));
                } catch (SlimNetworkException ex) {
                    Logger.getLogger(PodcastPanel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SlimException ex) {
                    Logger.getLogger(PodcastPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } finally {
            this.setCursor(Utils.getNormalCursor());
        }
}//GEN-LAST:event_btnClearAndPlayActionPerformed

    private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
        listPodcasts();
    }//GEN-LAST:event_btnRefreshActionPerformed

    private void podcastTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_podcastTreeValueChanged
        loadProgressItems.setVisible(true);
        podcastTree.setEnabled(false);
        podcastItemList.setEnabled(false);
        new Thread(new Runnable() {

            public void run() {
                try {
                    loadingItems = true;
                    SlimPodcastItem podcast = getPodcastTree().getSelectedPodcast();

                    if (podcast != null) {
                        getPodcaster().loadPodcastItem(podcast);
                        getPodcastItemList().setPodcastItems(podcast.getPodcastItems());
                        btnFavorite.setAction(new AddFavoriteAction(podcast));
                        btnFavorite.setText("Add Favorite");
                        btnFavorite.setEnabled(true);
                    } else {
                        btnFavorite.setEnabled(false);
                    }
                } finally {
                    podcastItemList.setEnabled(true);
                    podcastTree.setEnabled(true);
                    loadProgressItems.setVisible(false);
                    loadingItems = false;
                }
                loadDetails();
            }
        }).start();
    }//GEN-LAST:event_podcastTreeValueChanged

    private void podcastItemListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_podcastItemListValueChanged

        if (!loadingItems) {
            loadDetails();
        }

    }//GEN-LAST:event_podcastItemListValueChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddFeed;
    private javax.swing.JButton btnAddToPlaylist;
    private javax.swing.JButton btnClearAndPlay;
    private javax.swing.JButton btnFavorite;
    private javax.swing.JButton btnPlayNext;
    private javax.swing.JButton btnRefresh;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblError;
    private javax.swing.JProgressBar loadDetailProgressBar;
    private javax.swing.JProgressBar loadProgressBar;
    private javax.swing.JProgressBar loadProgressItems;
    private javax.swing.JPanel podcastInfoPanel;
    private javax.swing.JList podcastItemList;
    private javax.swing.JTree podcastTree;
    private javax.swing.JTextField tfAddFeed;
    // End of variables declaration//GEN-END:variables

    private PodcastTree getPodcastTree() {
        return (PodcastTree) podcastTree;
    }

    private void listPodcasts() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                loadProgressBar.setVisible(true);

                try {
                    try {
                        lblError.setVisible(false);
                        getPodcastTree().listAll();
                    } catch (Exception e) {
                        lblError.setText("Could not get podcast list");
                        lblError.setVisible(true);
                        e.printStackTrace();
                        //new ErrorDialog(Utils.getParentComponent(getPodcastTree()), "Could not get podcast list.", e, false, false);
                    }
                } finally {
                    loadProgressBar.setVisible(false);
                }
            }
        }).start();
    }

    /**
     * @return the playlist
     */
    public SlimPlaylist getPlaylist() {
        return playlist;
    }

    /**
     * @param playlist the playlist to set
     */
    public void setPlaylist(SlimPlaylist playlist) {
        this.playlist = playlist;
    }

    private PodcastItemList getPodcastItemList() {
        return (PodcastItemList) podcastItemList;
    }

    /**
     * @return the podcaster
     */
    public SlimPodcaster getPodcaster() {
        return podcaster;
    }

    /**
     * @param podcaster the podcaster to set
     */
    public void setPodcaster(SlimPodcaster podcaster) {
        this.podcaster = podcaster;
    }

    private PodcastInfoPanel getPodcastInfoPanel() {
        return (PodcastInfoPanel)podcastInfoPanel;
    }

    private void loadDetails() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    loadDetailProgressBar.setVisible(true);
                    podcastTree.setEnabled(false);
                    podcastItemList.setEnabled(false);
                    getPodcastInfoPanel().setSongInfo(getPodcaster().getPodcastAudioDetails(getPodcastItemList().getSelectedPodcast()));
                } catch (SlimNetworkException ex) {
                    Logger.getLogger(PodcastPanel.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    loadDetailProgressBar.setVisible(false);
                    podcastTree.setEnabled(true);
                    podcastItemList.setEnabled(true);
                }
            }
        }).start();
    }
}
